package com.lzj.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzj.admin.pojo.*;
import com.lzj.admin.mapper.ReturnListMapper;
import com.lzj.admin.query.ReturnListQuery;
import com.lzj.admin.service.IGoodsService;
import com.lzj.admin.service.IReturnListGoodsService;
import com.lzj.admin.service.IReturnListService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzj.admin.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 退货单表 服务实现类
 * </p>
 *
 * @author luoyoumou
 * @date 2022-12-15
 */
@Service
public class ReturnListServiceImpl extends ServiceImpl<ReturnListMapper, ReturnList> implements IReturnListService {

    @Resource
    private IReturnListGoodsService returnListGoodsService;

    @Resource
    private IGoodsService goodsService;

    /**
     * 显示退货单号
     * @return
     */
    @Override
    public Object getNextReturnNumber() {

        try {
            StringBuffer sb = new StringBuffer();
            //固定TH
            sb.append("TH");
            //TH后获取当前时间
            sb.append(DateUtil.getCurrentDateStr());
            String returnNumber = this.baseMapper.getNextReturnNumber();
            //如果退货单号不为空
            if (returnNumber != null) {
                //在当前货单后递增
                sb.append(StringUtil.formatCode(returnNumber));
            }else {
                //为空则设当前货单为第一个
                sb.append("0001");
            }
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }


    /**
     * 商品退货接口实现
     * @param returnList
     * @param rlgList
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void saveReturnList(ReturnList returnList, List<ReturnListGoods> rlgList) {
        AssertUtil.isTrue(null == returnList.getSupplierId() || 0 == returnList.getSupplierId() ,"请选择供应商！");
        AssertUtil.isTrue(CollectionUtils.isEmpty(rlgList),"请添加商品！");
        AssertUtil.isTrue(null == returnList.getAmountPaid() || 0 >= returnList.getAmountPaid() ,"实退金额 必须 >0 ！");
        returnList.setCreateDate(new Date());
        AssertUtil.isTrue(!(this.save(returnList)),"记录添加失败!");
        ReturnList  temp = this.getOne(new QueryWrapper<ReturnList>().eq("return_number",returnList.getReturnNumber()));
        rlgList.forEach(rlg->{
            AssertUtil.isTrue(null == rlg.getNum() || 1 > rlg.getNum(),"请检查：每件商品的 数量 必须 >=1 ！");
            rlg.setReturnListId(temp.getId());
            rlg.setFpyName(PinYinUtil.getFirstSpell(rlg.getName()));
            Goods goods =goodsService.getById(rlg.getGoodsId());
            // 检查库存
            AssertUtil.isTrue(goods.getInventoryQuantity()< rlg.getNum(),"商品 "+ goods.getName() +" 的库存数量不足，，操作失败！");
            goods.setInventoryQuantity(goods.getInventoryQuantity()-rlg.getNum());
            goods.setState(2);
            goodsService.updateById(goods);

        });
        AssertUtil.isTrue(!(returnListGoodsService.saveBatch(rlgList)),"记录添加失败!");
    }

    /**
     * 退货单据查询接口实现
     * @param returnListQuery
     * @return
     */
    @Override
    public Map<String, Object> returnList(ReturnListQuery returnListQuery) {
        //准备分页参数
        IPage<ReturnList> page = new Page<ReturnList>(returnListQuery.getPage(),returnListQuery.getLimit());
        page =  this.baseMapper.returnList(page,returnListQuery);
        return PageResultUtil.getResult(page.getTotal(),page.getRecords());
    }

    /**
     * 退货单删除接口实现
     * @param id
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public void deleteReturnList(Integer id) {
        AssertUtil.isTrue(!(returnListGoodsService.remove(new QueryWrapper<ReturnListGoods>().eq("return_list_id",id))),"记录删除失败!");
        AssertUtil.isTrue(!(this.removeById(id)),"记录删除失败!");
    }

}
